<template>
  <div class="container">
    <el-input placeholder="请输入溯源码" v-model.number="traceNumber" clearable class="input">
    </el-input>
    <el-button type="primary" @click="addGoods" class="button-add">添加商品信息</el-button>
    <el-button type="danger" @click="logout" class="button-logout" >退出</el-button>

    <!-- 商品流转信息列表 -->
    <el-table :data="renderList" class="custom-table" :default-sort="{ prop: 'date', order: 'descending' }">
      <el-table-column prop="traceNumber" label="溯源码">
        <template slot-scope="scope">
          <!-- 鼠标点击商品细节弹窗信息 -->
          <el-popover trigger="click" placement="top" @show="handlePopover(scope.row)" :width="700">
            <GoodDetail :good="popoverData" :block_pro="block_pro" :user="user"/>
            <div slot="reference">
              <span class="trace-number">{{ scope.row.traceNumber }}</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称">
      </el-table-column>
      <el-table-column prop="date" label="上架时间" sortable>
      </el-table-column>
      <el-table-column prop="quality" label="质检情况">
      </el-table-column>
      <el-table-column prop="from" label="发货单位">
      </el-table-column>
      <el-table-column prop="to" label="收货单位">
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination class="custom-pagination" background :hide-on-single-page="false"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currPage"
                   :page-sizes="[10, 20, 50]" :page-size.sync="pageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>
    <!-- 添加商品信息组件 -->
    <addGoods :dialogFormVisible="popup" :user="1" :good="goodDetail" :block_pro="block_pro" @popup="handlePopup"
              @confirmPopup="formSubmit" />
  </div>
</template>

<script>
import axios from 'axios';
import GoodDetail from '../components/GoodDetail.vue';
import addGoods from '../components/addGoods.vue';

export default {
  name: 'Distributor',
  // 注册添加商品信息、商品详情子组件
  components: {
    addGoods,
    GoodDetail
  },

  data() {
    return {
      popup: false, // 控制添加商品信息弹窗
      traceNumber: '', // 溯源码
      goodDetail: '', // 溯源商品信息
      goodList: [], // 商品信息列表
      popoverData: {}, // 弹窗商品信息数据
      block_pro: {},   // 区块链信息
      currPage: 1, // 当前页
      pageSize: 10, // 每页显示数据
      total: 0, // 总数据
      user: 1
    }
  },
  computed: {
    // 当前页的数据渲染
    renderList() {
      return this.goodList.slice((this.currPage - 1) * this.pageSize, this.currPage * this.pageSize);
    }
  },
  mounted() {
    // 获取数据
    this.getData();
  },
  methods: {
    logout() {
      // 跳转到登录界面
      this.$router.push({ name: 'loginview' });
      this.$emit('logout', '');
    },
    // 获取商品信息
    getGoods() {
      axios({
        method: 'get',
        url: `/trace?traceNumber=${this.traceNumber}`
      }).then(ret => {
        this.goodDetail = ret.data || [];
      })
          .catch(err => {
            alert("没有该溯源码");
            console.log(err);
          });
    },
    // 数据获取，根据 user 用户类型来分别获取供应商和零售商的数据
    getData() {
      let pathname = this.user === 1 ? 'distributing' : 'retailing';
      axios({
        method: 'get',
        url: `/${pathname}`
      })
          .then(ret => {
            this.goodList = ret.data
                .map(item => {
                  let quality = item.quality === 0 ? '优质' : item.quality === 1 ? '合格' : '不合格';
                  return ({
                    ...item,
                    date: this.$dateTime(item.timestamp),
                    quality,
                  });
                })
                .reverse();
            this.total = this.goodList.length;
          })
          .catch(err => {
            console.log(err);
          });
    },
    // 表格中商品详情弹窗
    async handlePopover(data) {
      // 供应商已有的信息足有支持显示，不需要进行额外 http 请求
      if (this.user === 1) {
        axios({
          method: 'get',
          url: `/trace?traceNumber=${data.traceNumber}`
        }).then(ret => {
          this.popoverData = ret.data[1] || [];
          console.log(this.popoverData);
          this.popoverData.produceLocation = ret.data[0].location;
          this.popoverData.produceTime = ret.data[0].produce_time;
          console.log(this.popoverData);
        });
        await axios({
          method: 'post',
          url: `/getBlockInfo`,
          data: {
            type: "producer",
            traceNumber: data.traceNumber
          }
        }).then(ret => {
          this.popoverData = ret.data[0] || [];
          console.log(this.popoverData);
          this.block_pro = ret.data.blockInfo;
          console.log(ret.data.blockInfo);
        });
      }
    },
    // 处理添加商品信息
    addGoods() {
      if (!this.traceNumber) {
        this.$message.error('请输入溯源码');
        return;
      }
      axios({
        method: 'get',
        url: `/trace?traceNumber=${this.traceNumber}`
      })
          .then(async ret => {
            this.goodDetail = ret.data || [];
            this.popup = true;

            // 供应商已有的信息足有支持显示，不需要进行额外 http 请求
            await axios({
              method: 'post',
              url: `/getBlockInfo`,
              data: {
                type: "producer",
                traceNumber: ret.data[0].traceNumber
              }
            }).then(ret => {
              this.block_pro = ret.data.blockInfo;
              console.log(ret.data.blockInfo);
            });
          })
          .catch(err => {
            alert("没有该溯源码");
            console.log(err);
          });
    },
    // 添加商品信息弹窗
    handlePopup(val) {
      this.popup = val;
    },
    formSubmit(val) {
      axios({
        method: 'post',
        url: `/addDistribution`,
        data: {
          ...val,
          quality: parseInt(val.quality),
          traceNumber: this.goodDetail[0].traceNumber,
          distributorAddress: localStorage.getItem('account')
        }
      })
          .then(ret => {
            if (ret.data.ret !== 1) {
              this.$message({
                message: '提交失败',
                type: 'error',
                center: true
              });
              return;
            }
            this.$blockInfo.setBlockInfo("Dis" + this.goodDetail[0].traceNumber, ret.data.data);
            this.$message({
              message: '提交成功',
              type: 'success',
              center: true
            });
            this.getData();
          })
          .catch(err => {
            console.log(err);
          });
      this.popup = false;
    },

    // 处理每页数据渲染数
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 处理翻页
    handleCurrentChange(val) {
      this.currPage = val;
    },
  }
}
</script>

<style scoped>

.container {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8); /* 稍微透明的白色背景 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  margin: 20px auto;
  max-width: 1200px;
}

.input {
  width: 300px;
  margin-bottom: 20px;
}

.button-add {
  margin-left: 5px;
  margin-bottom: 20px;
  background-color: #007bff; /* 更亮的蓝色 */
  border-color: #007bff;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.button-add:hover {
  background-color: #0056b3; /* 悬停时的颜色 */
  border-color: #0056b3;
}

.button-logout {
  float: right;
  margin-bottom: 20px;
  background-color: #dc3545; /* 红色 */
  border-color: #dc3545;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.button-logout:hover {
  background-color: #c82333; /* 悬停时的颜色 */
  border-color: #c82333;
}

.custom-table {
  width: 100%;
  background-color: white;
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.trace-number {
  color: #007bff;
  cursor: pointer;
  text-decoration: underline;
}

.custom-pagination {
  margin-top: 20px;
  background-color: white;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  text-align: center;
}
</style>
